package com.zrrd.yunchmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zrrd.yunchmall.order.client.ProductServiceClient;
import com.zrrd.yunchmall.order.entity.Order;
import com.zrrd.yunchmall.order.entity.OrderOperateHistory;
import com.zrrd.yunchmall.order.mapper.OrderMapper;
import com.zrrd.yunchmall.order.mapper.OrderOperateHistoryMapper;
import com.zrrd.yunchmall.order.service.IOrderItemService;
import com.zrrd.yunchmall.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yunchmall.user.entity.Admin;
import com.zrrd.yunchmall.util.ResponseResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author LYY
 * @since 2024-01-15
 */
@Service
@SuppressWarnings("all")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderOperateHistoryMapper historyMapper;

    @Autowired
    private ProductServiceClient productServiceClient;

    @Autowired
    private IOrderItemService OrderItemService;

    @Autowired
    private IOrderService orderService;


    @Override
    //只能用于管理本地事务,第三步需要跨服务完成,会产生分布式事务问题(找Seata帮忙)
    @Transactional
    //@GlobalTransactional
    public void closeOrder(String ids, String note) {
        //1.修改订单状态
        List<Order> orderList = super.listByIds(Arrays.asList(ids.split(",")));
        orderList.forEach(order -> {
            //表示订单已关闭
            order.setStatus(4);
            //2.记录日志
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(order.getId());
            history.setOrderStatus(4);
            history.setNote(note);
            history.setOperateMan("当前登录管理员");
            historyMapper.insert(history);
            //3.释放库存(需要调用商品服务完成)
            List<Map<String, Object>> params = new LinkedList<>();
            QueryWrapper queryWrapper = new QueryWrapper<>();
            //select product_id as productId,product_sku_id as skuId,product_quantity as quantity
            //from oms_order_item
            //where order_id=?
            queryWrapper.eq("order_id", order.getId());
            queryWrapper.select("product_id as productId",
                    "product_sku_id as skuId",
                    "product_quantity as quantity");
            //远程调用商品服务释放内存
            params = OrderItemService.listMaps(queryWrapper);
        });
        super.updateBatchById(orderList);

    }

    @Override
    public void returnCoupon(String ids) {

    }

    @Override
    public void delivery(List<Map<String, Object>> params) {
        //1 循环遍历集合
        params.forEach(item -> {
            //2 设置条件，执行update操作
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", item.get("orderId"));
            updateWrapper.set("status", 2);
            updateWrapper.set("delivery_company", item.get("deliveryCompany"));
            updateWrapper.set("delivery_sn", item.get("deliverySn"));
            updateWrapper.set("delivery_time", LocalDateTime.now());
            super.update(updateWrapper);
            //3 记录操作日志
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(Long.valueOf(item.get("orderId").toString()));
            history.setOrderStatus(2);
            history.setNote("订单发货");
            history.setOperateMan("当前登录管理员");
            historyMapper.insert(history);// 记录这次修改
        });
    }
    @Transactional
    @Override
    public void remove(String ids, Admin admin) {
        //1.遍历订单id
        for (String orderId : ids.split(",")) {
            QueryWrapper queryWrapper=new QueryWrapper<>();
            queryWrapper.select("status");
            queryWrapper.eq("id",orderId);
            Order order=super.getOne(queryWrapper);
            //订单id存在,且订单状态满足删除条件
            if (order!=null&&order.getStatus()==4||order.getStatus()==5){
                UpdateWrapper updateWrapper=new UpdateWrapper<>();
                updateWrapper.set("delete_stutus",1);
                updateWrapper.in("id",orderId);
                super.update(updateWrapper);
                //3 记录操作日志
                OrderOperateHistory history = new OrderOperateHistory();
                history.setOrderId(Long.valueOf(orderId));
                history.setOrderStatus(6);
                history.setNote("订单发货");
                history.setOperateMan(admin.getId()+","+admin.getUsername());
                historyMapper.insert(history);// 记录这次修改
            }
        }
        //2.删除满足条件的订单(状态为4和5的订单)
        //3.记录操作日志
    }

    @Override
    public void updateReceiverInfo(Map<String, Object> params,Admin admin) {
        //1.修改信息
        UpdateWrapper updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",params.get("orderId"));
        updateWrapper.set("receiver_name",params.get("receiverName"));
        updateWrapper.set("receiver_phone",params.get("receiverPhone"));
        updateWrapper.set("receiver_post_code",params.get("receiverPostCode"));
        updateWrapper.set("receiver_province",params.get("receiverProvince"));
        updateWrapper.set("receiver_city",params.get("receiverCity"));
        updateWrapper.set("receiver_region",params.get("receiverRegion"));
        updateWrapper.set("receiver_detail_address",params.get("receiverDetailAddress"));
        super.update(updateWrapper);
        //2.添加操作历史
        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(Long.valueOf(params.get("orderId").toString()));
        history.setNote("订单发货");
        history.setOperateMan(admin.getId()+","+admin.getUsername());
        historyMapper.insert(history);// 记录这次修改
    }

    @Override
    public void updateMoneyInfo(Map<String, Object> params, Admin admin) {
        Order order=super.getById(Long.valueOf(params.get("orderId").toString()));
        float newFreighAmount=0f;
        if (params.get("freightAmount")!=null){
            newFreighAmount=Float.valueOf(params.get("freightAmount").toString());
        }
        float discountAmount=0f;
        if (params.get("discountAmount")!=null){
            discountAmount=Float.valueOf(params.get("discountAmount").toString());
        }
        order.setFreightAmount(BigDecimal.valueOf(newFreighAmount));
        order.setDiscountAmount(BigDecimal.valueOf(discountAmount));
        float totalAmount=order.getTotalAmount().floatValue();
        float promotionAomunt=order.getPromotionAmount().floatValue();
        float intgrationAmount=order.getIntegrationAmount().floatValue();
        float couponAmount=order.getCouponAmount().floatValue();
        /*
        实际支付金额(payAmount)=商品合计(totalAmount)+运费(freighAmount)
                                                -(活动减免)promotion_amount
                                                -(折扣费用)discount_amount
                                                -(积分抵扣)integration_amount
                                                -(优惠卷)coupon_amount

        */
        float payAmount=totalAmount+newFreighAmount+newFreighAmount
                -promotionAomunt
                -discountAmount
                -intgrationAmount
                -couponAmount;
        order.setPayAmount(BigDecimal.valueOf(payAmount));
        super.updateById(order);
        //2.添加操作历史
        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(order.getId());
        history.setNote("修改费用信息");
        history.setOperateMan(admin.getId()+","+admin.getUsername());
        historyMapper.insert(history);// 记录这次修改
    }
}
